
import { verifiToken } from '../apis'

class Http {
	constructor() {
		this.timeout = 15000
		this.reqHeader = {
			'Content-Type': 'applicaton/json',
			'token': localStorage.getItem('token')
		}
		this.dataType = 'json'
	}
	
	async getToken() {
		const token = localStorage.getItem('token')
		if (token) {
			return await verifiToken(token)
		} else {
			this.verifiTokenFailFunc()
			throw new Error('登录失效，请重新登录')
		}
	}

	verifiTokenFailFunc() {
		uni.redirectTo({
			url: '/pages/login'
		})
	}
	
	async request(method = "GET", url, data = {}) {
		const needVerifiToken = !url.includes('login') && !url.includes('token')

		needVerifiToken && await this.getToken()
		return new Promise((resolve, reject) => {
			uni.showLoading({
				title: ''
			})
			resolve(
				uni.request({
					method,
					url,
					data,
					header: this.reqHeader,
					timeout: this.timeout,
					dataType: this.dataType
				})
			)
		})
		.then(([_, res]) => {
			uni.hideLoading()
			const { code, msg } = res.data
			// TODO: code 类型统一 string
			if (code != '200') {
				uni.showToast({ icon: 'none', title: msg })
				throw new Error(msg)
			}
			return res.data
		})
		.catch(err => {
			uni.hideLoading()
			needVerifiToken && this.verifiTokenFailFunc()
			console.log('请求失败 => ', err)
		})
	}
	
	
	// .. other methods
}

export default new Http()